package com.iweb.newa202104.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.iweb.newa202104.dto.UserOutputDTO;
import com.iweb.newa202104.util.CommonUtil;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: LGZ
 * @Date: 2021/5/11 22:40
 * @Description:
 */
public class FilterUtil {
    public static void commonFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain, int PRE_URL_LENGTH, String[] EXCLUDE_URL) throws IOException, ServletException {
        boolean flag = false;
        String url = ((HttpServletRequest) servletRequest).getServletPath().substring(PRE_URL_LENGTH);
        for (String s : EXCLUDE_URL) {
            if(url.equals(s)){
                flag = true;
                break;
            }
        }
        UserOutputDTO user = (UserOutputDTO)((HttpServletRequest) servletRequest).getSession().getAttribute("user");

        /*
         * flag == true 访问的地址被排除 （不需要权限） 如登录，注册
         * user != null 即已经 flag == false 访问的地址需要权限，那么只有session中有登录信息才可以访问
         */
        if (flag || user != null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            servletResponse.setContentType("application/json;charset=utf-8");
            PrintWriter writer = servletResponse.getWriter();
            ObjectMapper mapper = new ObjectMapper();
            writer.print(mapper.writeValueAsString(CommonUtil.ajaxReturn(400, "无此权限")));
        }
    }

}
